package com.efast.dmom.mgmt.controller.mes;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.ResultType;

import com.efast.cafe.framework.bean.ResultBean;
import com.efast.cafe.framework.exception.ServiceException;
import com.efast.dmom.mgmt.bean.mes.LabelPrintDto;
import com.efast.dmom.mgmt.bean.mes.ProductExcuteDto;
import com.efast.dmom.mgmt.bean.mes.ReportDto;
import com.efast.dmom.mgmt.bean.mes.WorkOrderInfoDto;
import com.efast.dmom.mgmt.dao.mes.TwBasLotDao;
import com.efast.dmom.mgmt.entity.mes.TwBasLot;
import com.efast.dmom.mgmt.service.mes.TwBasLotService;
import com.efast.dmom.mgmt.utils.MesConstant;
import com.efast.dmom.mgmt.utils.PrintCardUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

@Controller
@RequestMapping(value = "/twBasLot")
public class TwBasLotController {
	@Autowired
	private TwBasLotService twBasLotService;
	@Autowired
	private TwBasLotDao twBasLotDao;

	// 保存产品执行中填写的数据，如物料消耗，检测，数据采集
	@RequestMapping(value = "/doSaveDatas")
	public @ResponseBody ResultBean doSaveDatas(@RequestBody ProductExcuteDto dto) {
		ResultBean result = new ResultBean(true, "'");
		String errorMsg = twBasLotService.doSaveDatas(dto);
		if (StringUtils.isNotBlank(errorMsg)) {
			throw new ServiceException(errorMsg.substring(0, errorMsg.length() - 1));
		} else {
			result.setMessage("保存成功！");
		}
		return result;
	}

	@RequestMapping(value = "/generateVin/{bsn}/{vin}")
	public @ResponseBody ResultBean generateVin(@PathVariable("bsn") String bsn, @PathVariable("vin") String vin) {
		ResultBean generateVin = twBasLotService.generateVin(bsn, vin);
		return generateVin;
	}

	// 校验是否vin已被使用
	@RequestMapping(value = "/validateVIN/{bsn}/{vin}")
	public @ResponseBody ResultBean validateVIN(@PathVariable("bsn") String bsn, @PathVariable("vin") String vin) {
		ResultBean validateVIN = twBasLotService.validateVIN(bsn, vin);
		return validateVIN;
	}

	// 产品执行中处理lot数据：更新状态并记录历史数据
	@RequestMapping(value = "/dealLotDatas")
	public @ResponseBody ResultBean dealLotDatas(@RequestBody ProductExcuteDto dto) {
		ResultBean result = new ResultBean(true, "'");
		twBasLotService.dealLotDatas(dto);
		return result;
	}

	// 产品执行中如果是合拼工位处理lot数据：更新状态并记录历史数据
	@RequestMapping(value = "/dealSpliceSelfnumber")
	public @ResponseBody ResultBean dealSpliceSelfnumber(@RequestBody ProductExcuteDto dto) {
		ResultBean result = new ResultBean(true, "'");
		twBasLotService.dealSpliceSelfnumber(dto);
		return result;
	}

	// 产品执行中校验lot中是否有保存采集数据
	@RequestMapping(value = "/dealRowDate")
	public @ResponseBody ResultBean dealRowDate(@RequestBody TwBasLot lot) {
		ResultBean result = new ResultBean();
		boolean dealRowDate = twBasLotService.dealRowDate(lot);
		result.setSuccess(dealRowDate);
		return result;
	}

	// 通过成品lotName获取成品信息
	@RequestMapping(value = "/selectLotByName")
	public @ResponseBody ResultBean selectLotByName(@RequestBody Map<Object, Object> map) {
		ResultBean result = new ResultBean(true, "'");
		Map name = twBasLotService.selectTwBasLotByName((String) map.get("lotName"));
		result.setObject(name);
		return result;
	}

	// 产品装箱
	@RequestMapping(value = "/packingBox")
	public @ResponseBody ResultBean packingBox(@RequestBody Map<Object, Object> map) {
		ResultBean result = new ResultBean(true, "'");
		twBasLotService.packingBox(map);
		return result;
	}

	// 获取产线产能
	@RequestMapping(value = "/getLineCapacity")
	public @ResponseBody ResultBean getLineCapacity(@RequestBody Map<Object, Object> map) {
		ResultBean result = new ResultBean(true, "'");
		List<ReportDto> reportDtoList = twBasLotService.getLineCapacity((String) map.get("sDateView"),
				(String) map.get("eDateView"));
		if (reportDtoList != null && reportDtoList.size() > 0) {
			result.setObject(reportDtoList);
		} else {
			result.setSuccess(false);
			result.setMessage("指定时间段内无产能");
		}
		return result;
	}

	// 获取工位产能
	@RequestMapping(value = "/getStationCapacity")
	public @ResponseBody ResultBean getStationCapacity(@RequestBody Map<Object, Object> map) {
		ResultBean result = new ResultBean(true, "'");
		List<ReportDto> reportDtoList = twBasLotService.getStationCapacity((String) map.get("sDateView"),
				(String) map.get("eDateView"));
		if (reportDtoList != null && reportDtoList.size() > 0) {
			result.setObject(reportDtoList);
		} else {
			result.setSuccess(false);
			result.setMessage("指定时间段内无产能");
		}
		return result;
	}

	// 指定产线下获取工位良率
	@RequestMapping(value = "/getStGoodRate")
	public @ResponseBody ResultBean getStGoodRate(@RequestBody Map<Object, Object> map) {
		ResultBean result = new ResultBean(true, "'");
		List<ReportDto> goodRateList = twBasLotService.getStGoodRate((String) map.get("lineName"),
				(String) map.get("sDateView"), (String) map.get("eDateView"));
		if (goodRateList != null && goodRateList.size() > 0) {
			result.setObject(goodRateList);
		} else {
			result.setSuccess(false);
			result.setMessage("指定产线的指定时间段内工位没有良率");
		}
		return result;
	}

	// 获取所有lot序号
	@RequestMapping(value = "/getAllLotName")
	public @ResponseBody ResultBean getAllLotName() {
		ResultBean result = new ResultBean(true, "'");
		List<TwBasLot> lotsList = twBasLotService.selectTwBasLot(null);
		result.setObject(lotsList);
		return result;
	}

	// 异常统计
	@RequestMapping(value = "/getAbnormalInfo")
	public @ResponseBody ResultBean getAbnormalInfo(@RequestBody ReportDto params) {
		ResultBean result = new ResultBean(true, "'");
		List<ReportDto> abInfoList = twBasLotService.getAbnormalInfo(params);
		if (abInfoList != null && abInfoList.size() > 0) {
			result.setObject(abInfoList);
		} else {
			result.setSuccess(false);
			result.setMessage("指定时间段内无不良记录");
		}
		return result;
	}

	// 产品入库
	@RequestMapping(value = "/doWarehousing")
	public @ResponseBody ResultBean doWarehousing(@RequestBody WorkOrderInfoDto dto) {
		ResultBean result = new ResultBean(true, "'");
		twBasLotService.doWarehousing(dto);
		return result;
	}

	// 判断lot是否有缺陷
	@RequestMapping(value = "/getDefFromLotName")
	public @ResponseBody ResultBean getDefFromLotName(@RequestBody Map<Object, Object> map) {
		boolean flag = false;
		ResultBean result = new ResultBean(true, "'");
//			TwBasLot lot = twBasLotService.getDefFromLotName((String)map.get("lotName"));
//			if(lot.getStatus().equals("close")) {
//				flag=true;
//			}
		result.setObject(true);
		return result;
	}

	// 流程卡打印
	@RequestMapping(value = "/printFlowCard")
	public @ResponseBody ResultBean printFlowCard(HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute TwBasLot lot) {
//		
		ResultBean result = new ResultBean(true, "'");
//		TwBasLot lot  = new TwBasLot() ; 
//		lot.setLotName("P2018050300000007");
		// 工艺流程卡模板文件地址
		String filePath = "jrxml/flowCard.jasper";
		// 获取要显示的数据，通过$F{key_name}获取
		List<LabelPrintDto> reportList = twBasLotDao.getFlowCardData(lot);
		// 填充参数，ireport中通过$P{key_name}获取
		Map<String, Object> parameters = new HashMap<String, Object>();
		if (reportList != null && reportList.size() > 0) {
			parameters.put("lotName", reportList.get(0).getLotName());
			parameters.put("partNoVersion", reportList.get(0).getPartNoVersion());
			parameters.put("routeName", reportList.get(0).getRouteName());
			parameters.put("partNameC", reportList.get(0).getPartNameC());
			parameters.put("routeVersion", reportList.get(0).getRouteVersion());
		}
		PrintCardUtil<LabelPrintDto> util = new PrintCardUtil<>(reportList);
		util.iReportWebPrintResponse(parameters, filePath, response);
//		twBasLotService.printFlowCard(lot);
		return result;
	}

	/**
	 * 返回iReport报表视图
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/printFlowCard1")
	public String report(HttpServletRequest request, HttpServletResponse response, Model model) {
		// 报表数据源
//		@RequestBody WorkOrderInfoDto dto,
//		WorkOrderInfoDto dto = new WorkOrderInfoDto() ;
//		dto.set
		TwBasLot lot = new TwBasLot();
		lot.setLotName("P2018050300000007");
		// 工艺流程卡模板文件地址
		String filePath = "jrxml/flowCard.jasper";
		// 获取要显示的数据，通过$F{key_name}获取
		List<LabelPrintDto> reportList = twBasLotDao.getFlowCardData(lot);
		// 填充参数，ireport中通过$P{key_name}获取
		Map<String, Object> parameters = new HashMap<String, Object>();
		if (reportList != null && reportList.size() > 0) {
			parameters.put("lotName", reportList.get(0).getLotName());
			parameters.put("partNoVersion", reportList.get(0).getPartNoVersion());
			parameters.put("routeName", reportList.get(0).getRouteName());
			parameters.put("partNameC", reportList.get(0).getPartNameC());
		}
		JasperPrint jasperPrint;
		JRDataSource jrDataSource;
//		try {
		if (reportList != null && reportList.size() > 0) {
			// 封装reportList中数据作为数据源 通过$F{key_name}获取
			jrDataSource = new JRBeanCollectionDataSource(reportList);
//				jasperPrint = JasperFillManager.fillReport(xmlPath, parameters, ds);
		} else {
			jrDataSource = new JREmptyDataSource();
//				jasperPrint = JasperFillManager.fillReport(xmlPath, parameters,ds);
		}
		// 替换掉导出的代码，true为弹出打印机设置，false为直接打印
//			JasperPrintManager.printReport(jasperPrint,true);
//		}
//	    JRDataSource jrDataSource = new JRBeanCollectionDataSource(JavaBeanPerson.getList());  

		// 动态指定报表模板url
		model.addAttribute("url", "/WEB-INF/jasper/flowCard.jasper");
		model.addAttribute("format", "pdf"); // 报表格式
		model.addAttribute("jrMainDataSource", jrDataSource);

		return "iReportView"; // 对应jasper-defs.xml中的bean id
	}

	@RequestMapping(value = "/closeLot")
	public @ResponseBody ResultBean closeLot(@RequestBody Map<String, Object> map) {
		ResultBean result = new ResultBean(true, "'");
		@SuppressWarnings({ "rawtypes", "unchecked" })
		ArrayList<Map> arrayValue = (ArrayList<Map>) map.get("params");
		for (Map<?, ?> mapValue : arrayValue) {
			List<TwBasLot> twBasLot =new ArrayList<TwBasLot>();
			TwBasLot data = new TwBasLot();
			String lotName = (String) mapValue.get("lotName");
			Integer lotID = (Integer) mapValue.get("lotId");
			Integer orderId = (Integer) mapValue.get("orderId");
			String sequence = (String) mapValue.get("sequence");
			String lotType = (String) mapValue.get("lotType");
			Integer orderItemId = (Integer) mapValue.get("orderItemId");
			data.setLotId(lotID);
			data.setOrderId(orderId);
			data.setSequence(sequence);
			data.setLotType(lotType);
			data.setOrderItemId(orderItemId);
			twBasLot.add(data);
			boolean flag = twBasLotService.closeLot(lotID);
			if (flag) {
				twBasLotService.updateWorkOrderStatus(MesConstant.WORK_ORDER_CLOSED,MesConstant.WORK_ORDER_ITEM_CLOSED,MesConstant.LOT_STATUS_CLOSED,twBasLot);
			} else {
				result.setSuccess(false);
				result.setMessage(result.getMessage() + lotName + "关闭失败;");
			}
		}
		return result;
	}

	@RequestMapping(value = "/scrapLot")
	public @ResponseBody ResultBean scrapLot(@RequestBody Map<String, Object> map) {
		ResultBean result = new ResultBean(true, "'");
		@SuppressWarnings({ "rawtypes", "unchecked" })
		ArrayList<Map> arrayValue = (ArrayList<Map>) map.get("params");
		for (Map<?, ?> mapValue : arrayValue) {
			String lotName = (String) mapValue.get("lotName");
			Integer lotID = (Integer) mapValue.get("lotId");
			boolean res = twBasLotService.scrapLot(lotID);
			if (res) {
				result.setSuccess(false);
				result.setMessage(result.getMessage() + lotName + "冻结失败;");
			}
		}
		return result;
	}

	// 当进行合拼功能时通过自编号查询指定信息
	@RequestMapping(value = "searchLotByselfNumber")
	public @ResponseBody ResultBean searchLotByselfNumber(@RequestBody Map<String,Object> map) {
		ResultBean searchLotByselfNumber = twBasLotService.searchLotByselfNumber(map);
		return searchLotByselfNumber;

	}

	// 产品执行中保存lot记录并记录历史数据
	@RequestMapping(value = "/dealSpliceLotDatas")
	public @ResponseBody ResultBean dealSpliceLotDatas(@RequestBody TwBasLot twBasLot) {
		ResultBean result = new ResultBean(true, "'");
		twBasLotService.dealSpliceLotDatas(twBasLot);
		return result;
	}

	// 通过VIN号和工位查询判断是否查询出数据
	@RequestMapping(value = "/valliVinExist")
	public @ResponseBody ResultBean valliVinExist(@RequestBody Map<String, Object> map) {
		ResultBean result = new ResultBean(true, "'");
		boolean valliVinExist = twBasLotService.valliVinExist(map);
		result.setObject(valliVinExist);
		return result;
	}

	// 通过lot的selfNumber查询lot
	@RequestMapping(value = "/selelotByctselfNumberAndlotName/{lotName}/{selfNumber}")
	public @ResponseBody ResultBean selelotByctselfNumberAndlotName(@PathVariable("lotName") String lotName,
			@PathVariable("selfNumber") String selfNumber) {
		ResultBean result = twBasLotService.selelotByctselfNumberAndlotName(lotName, selfNumber);
		return result;
	}

	// 冻结Lot
	@RequestMapping(value = "/freezeLot")
	public @ResponseBody ResultBean freezeLot(@RequestBody List<TwBasLot> twBasLot) {
		ResultBean result = twBasLotService.freezeLot(twBasLot);
		return result;
	}

	// 解冻Lot物理状态
	@RequestMapping(value = "/scrapLotState")
	public @ResponseBody ResultBean scrapLotState(@RequestBody List<TwBasLot> twBasLot) {
		ResultBean result = twBasLotService.scrapLotState(twBasLot);
		return result;
	}
}
